package cn.wolfcode.repository;


import cn.wolfcode.domain.Strategy;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class StrategyRepository {
    private static final String INDEX = "strategy";
    private final RestHighLevelClient client; //Elasticsearch数据库基于高阶版本的rest访问客户端
    //构建的过程中给client赋值
    public StrategyRepository(RestHighLevelClient client){
        this.client = client;
    }

    public String save(Strategy strategy) throws IOException {
        String json = JSON.toJSONString(strategy);
        IndexRequest request = new IndexRequest(INDEX)
                .id(strategy.getId())
                .source(json, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        return response.getId();
    }

    public Strategy getById(String id) throws IOException {
        GetRequest request = new GetRequest(INDEX, id);
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //根据id到es中查询，如果没有应答的结果
        if(!response.isExists()){
            return null;
        }
        String json = response.getSourceAsString();
        Strategy strategy = JSON.parseObject(json, Strategy.class);
        return strategy;
    }

    public List<Strategy> search(String query, int size) throws IOException {
        SearchSourceBuilder ssb = new SearchSourceBuilder()
                .query(QueryBuilders.multiMatchQuery(query, "title", "subTitle", "summary")
                        .type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
                .size(size);
        SearchRequest request = new SearchRequest(INDEX).source(ssb);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<Strategy> results = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            String json = hit.getSourceAsString();
            Strategy strategy = JSON.parseObject(json, Strategy.class);
            results.add(strategy);
        }
        return results;
    }

}

